/*
 * Copyright (c) 2014. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package net.NettyEngine3.core;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.*;

import static org.jboss.netty.channel.Channels.write;

/**
 *  * @author :石头哥哥<br/>
 *         Date: 13-3-29
 *         Time: 上午11:15
 *
 *        数据编码  发送
 *
 */
public final class NServerFrameEncoder implements ChannelDownstreamHandler {

    protected NServerFrameEncoder(){}

    @Override
    public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent evt) throws Exception {
        if (!(evt instanceof MessageEvent)) {
            ctx.sendDownstream(evt);
            return;
        }
        MessageEvent e = (MessageEvent) evt;
        if (!doEncode(ctx, e)) {
            ctx.sendDownstream(e);
        }
    }

    /**
     * do encode    MessageEvent to client
     * @param ctx
     * @param e
     * @return
     * @throws Exception
     */
    private boolean doEncode(ChannelHandlerContext ctx, MessageEvent e) throws Exception{
        Object message=e.getMessage();
        if (!( message instanceof ChannelBuffer))return false;
        write(ctx, e.getFuture(), message, e.getRemoteAddress());
        return true;
    }

}
